//过滤更新商品
import { useEffect, useState } from "react";
import CommonModal from "@/components/CommonModal";
import { message } from "antd";
import IconFont from "@/components/IconFont";
import { cloneDeep, isEmpty } from "lodash";
import { getAllSysIdByCondition, filterUpdateSysGoodsSku } from "./service";

/** 过滤更新商品 */
function FilterUpdateGoods(props) {
	const { onCancel: handleCancel, selectedRows, searchData, refresh } = props;

	const [isOk, setIsOk] = useState(false);

	const [open, setOpen] = useState(false);

	const textRender = () => {
		if (selectedRows.length) {
			return <span className="common-color1">已勾选</span>;
		} else {
			const obj = cloneDeep(searchData);
			delete obj.matchOrNot;
			if (Object.values(obj).every(value => value === undefined) && searchData.matchOrNot == "all") {
				return <span className="common-color9">全部</span>;
			} else {
				return <span className="common-color1">筛选后</span>;
			}
		}
	};

	useEffect(() => {
		setOpen(true);
	}, []);

	//根据条件获取所有系统商品id
	const handleGetAllSysIdByCondition = async () => {
		START_LOADING();
		const { success, data = [] } = await getAllSysIdByCondition({
			...searchData,
			matchOrNot: searchData.matchOrNot == "all" ? "" : searchData.matchOrNot
		});
		END_LOADING();
		const obj = cloneDeep(searchData);
		delete obj.matchOrNot;
		if (success) {
			handleSubmit(data, Object.values(obj).every(value => value === undefined) && searchData.matchOrNot == "all" ? true : false);
		}
	};

	//保存
	const handleSubmit = async (ids, allUpdateFlag) => {
		START_LOADING();
		const { success, msg = "操作成功" } = await filterUpdateSysGoodsSku({
			ids,
			allUpdateFlag
		});
		END_LOADING();
		if (success) {
			message.success(msg);
			setIsOk(true);
			setOpen(false);
		}
	};

	//点击确定
	const onOk = () => {
		if (selectedRows.length) {
			handleSubmit(
				selectedRows.map(item => item.id),
				false
			);
		} else {
			handleGetAllSysIdByCondition();
		}
	};

	const onCancel = () => {
		setOpen(false);
	};

	const afterClose = () => {
		if (isOk) {
			setTimeout(() => {
				refresh();
			}, 100);
            handleCancel();
		} else {
			handleCancel();
		}
	};

	return (
		<CommonModal
			minHeight={"100px"}
			title="过滤更新商品"
			afterClose={afterClose}
			open={open}
			width="600px"
			onOk={onOk}
			onCancel={onCancel}
		>
			<p>
				<IconFont type="iconjingshi" style={{ fontSize: "20px", padding: "5px" }} />
				是否根据“自动生成”设置中，系统商品字段的过滤规则，重新过滤并更新{textRender()}的商品？
			</p>
		</CommonModal>
	);
}

export default FilterUpdateGoods;
